package helper

import (
	"chatgpt/helper/code"
	"github.com/gin-gonic/gin"
	"github.com/slclub/go-tips"
	"github.com/slclub/go-tips/stringbyte"
	"io"
	"net/http"
)

// interface
type Writer interface {
	io.Writer
	WriteAppend(b []byte) (int, error)
}

// struct

type Response struct {
	MsgCode int
	Desc    string
	Data    any
	Tokens  int
}

func Echo(ctx *gin.Context, codeno any, data any, toks ...int) {
	co := 0
	switch val := codeno.(type) {
	case code.CODENO:
		co = int(val)
	case int:
		co = val
	case rune:
		co = int(val)
	default:
		co = tips.Int(val)
	}
	desc := code.CODENO(tips.Int(codeno))
	tokens := 0
	if len(toks) > 0 {
		tokens = toks[0]
	}
	ctx.JSON(http.StatusOK, &Response{MsgCode: co, Data: data, Desc: desc.String(), Tokens: tokens})
}

func Count(ctx *gin.Context, codeno code.CODENO, data any) {
	ctx.JSON(http.StatusOK, &Response{MsgCode: int(codeno), Data: data, Desc: codeno.String()})
}

type ResponseDesc struct {
	MsgCode code.CODENO
	Desc    string
	Data    any
	Tokens  int
}

func (self *ResponseDesc) Write(b []byte) (int, error) {
	if b == nil {
		self.Data = nil
		return 0, nil
	}
	data := stringbyte.BytesToString(b)
	self.Data = data
	return len(b), nil
}

func (self *ResponseDesc) WriteAppend(b []byte) (int, error) {
	data := stringbyte.BytesToString(b)
	if self.Data == nil {
		self.Data = data
		return len(b), nil
	}
	self.Data = self.Data.(string) + data
	return len(b), nil
}
